package com.ruoyi.system.wnjk.test.rabbitmq.dead.test;

import com.rabbitmq.client.*;
import com.ruoyi.system.wnjk.test.rabbitmq.RabbitMQInfo;

import java.util.HashMap;
import java.util.Map;

public class RabbitMQDLQExample {

    private final static String EXCHANGE_NAME = "dlx_exchange";
    private final static String NORMAL_QUEUE_NAME = "normal_queue";
    private final static String DEAD_LETTER_QUEUE_NAME = "dead_letter_queue";

    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(RabbitMQInfo.Info.HOST);
        factory.setPort(RabbitMQInfo.Info.PORT);
        factory.setUsername(RabbitMQInfo.Info.USER_NAME);
        factory.setPassword(RabbitMQInfo.Info.PASS_WORD);
        factory.setVirtualHost("/");


        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {

            // 声明死信交换机和死信队列
            declareDeadLetterQueue(channel);

            // 声明普通队列，并设置死信交换机
            declareNormalQueueWithDLX(channel);

            // 生产者发送消息到普通队列
            produceMessages(channel);

            // 消费者从普通队列和死信队列接收消息
            consumeMessages(channel);
        }
    }


    private static void declareDeadLetterQueue(Channel channel) throws Exception {
        // 声明死信交换机
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT, true);

        // 声明死信队列
        Map<String, Object> deadLetterArgs = new HashMap<>();
        channel.queueDeclare(DEAD_LETTER_QUEUE_NAME, true, false, false, deadLetterArgs);

        // 绑定死信队列到死信交换机
        channel.queueBind(DEAD_LETTER_QUEUE_NAME, EXCHANGE_NAME, DEAD_LETTER_QUEUE_NAME);
    }

    private static void declareNormalQueueWithDLX(Channel channel) throws Exception {
        // 设置普通队列的参数，包括死信交换机
        Map<String, Object> args = new HashMap<>();
        args.put("x-dead-letter-exchange", EXCHANGE_NAME);
        args.put("x-message-ttl", 10000); // 设置消息的TTL为10秒

        // 声明普通队列
        channel.queueDeclare(NORMAL_QUEUE_NAME, true, false, false, args);

        // 直接发送消息到默认交换机，无需绑定
        // 默认交换机会根据路由键直接将消息发送到相应的队列
    }

    private static void produceMessages(Channel channel) throws Exception {
        for (int i = 0; i < 5; i++) {
            String message = "Message " + i;
            // 发送消息到普通队列，使用默认交换机
            channel.basicPublish("", NORMAL_QUEUE_NAME, null, message.getBytes());
            System.out.println(" [x] Sent '" + message + "'");
        }
    }

    private static void consumeMessages(Channel channel) throws Exception {
        DeliverCallback normalCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received from normal queue: '" + message + "'");
            // 模拟处理失败的情况
            if (Math.random() > 0.5) {
                System.out.println(" [x] Message processed successfully.");
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            } else {
                System.out.println(" [x] Failed to process message.");
                // 不确认消息，使其重新入队
                channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, true);
            }
        };

        DeliverCallback deadLetterCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received from dead letter queue: '" + message + "'");
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        };

        // 消费普通队列中的消息
        channel.basicConsume(NORMAL_QUEUE_NAME, false, normalCallback, consumerTag -> {});

        // 消费死信队列中的消息
        channel.basicConsume(DEAD_LETTER_QUEUE_NAME, true, deadLetterCallback, consumerTag -> {});
    }
}
